//
//  XMPositionSelectView.m
//  XMJJ_zmy
//
//  Created by 丁浩 on 2025/7/14.
//

#import "XMPositionSelectView.h"
#import <Mapkit/Mapkit.h>

@interface XMPositionSelectView () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tbl;

@property (nonatomic, strong) UITextField *searchTextField;

@property (nonatomic, strong) NSArray *locations;

@end

@implementation XMPositionSelectView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self creatUI];
    }
    return self;
}

- (void)creatUI {
    [self addSubview:self.navView];
    self.navTitleLabel.text = @"所在位置";
//    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(16.0) frame:CGRectMake(0, kNavagationBarH - 44, 44, 44) title:@"取消" titleColor:kColorHEX(0x666666)];
//    [cancelBtn addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.navView addSubview:cancelBtn];
    
//    UIButton *completeBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(16.0) frame:CGRectMake(self.width - 44, kNavagationBarH - 44, 44, 44) title:@"完成" titleColor:kColorHEX(0x3333333)];
//    [completeBtn addTarget:self action:@selector(completeAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.navView addSubview:completeBtn];
    [self addSubview:self.tbl];
    
    [self addSubview:self.searchTextField];
}

- (void)setContentWithLocationArr:(NSArray *)location {
    self.locations = location;
    [_tbl reloadData];
}

//完成
//- (void)completeAction:(UIButton *)button {
//
//}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.text.length > 0) {
        MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
        request.naturalLanguageQuery = textField.text;
//        request.region
        MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];
        XMWeakSelf;
        [localSearch startWithCompletionHandler:^(MKLocalSearchResponse * _Nullable response, NSError * _Nullable error) {
            weakSelf.locations = response.mapItems;
            [weakSelf.tbl reloadData];
        }];
    }
    return YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.locations.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return KScaleWidth(50.0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellName = @"XMPositionSelectViewName";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellName];
        cell.textLabel.font = KFontSize(14.0);
        cell.textLabel.textColor = kColorHEX(0x333333);
        cell.detailTextLabel.font = KFontSize(12.0);
        cell.detailTextLabel.textColor = kColorHEX(0x666666);
    }
    id location = self.locations[indexPath.row];
    if ([location isKindOfClass:[CLPlacemark class]]) {
        CLPlacemark *placemark = self.locations[indexPath.row];
        cell.textLabel.text = [NSString stringWithFormat:@"%@%@", placemark.thoroughfare, placemark.name];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@%@%@",  placemark.country, placemark.locality, placemark.thoroughfare, placemark.name];
    }
    else {
        MKMapItem *item = self.locations[indexPath.row];
        CLPlacemark *placemark = item.placemark;
        cell.textLabel.text = [NSString stringWithFormat:@"%@", item.name];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@%@%@%@",  placemark.administrativeArea, placemark.locality, placemark.subLocality, placemark.thoroughfare, placemark.name];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    id location = self.locations[indexPath.row];
    NSString *name = @"";
    CLPlacemark *selectMark;
    if ([location isKindOfClass:[CLPlacemark class]]) {
        CLPlacemark *placemark = self.locations[indexPath.row];
        name = [NSString stringWithFormat:@"%@%@", placemark.thoroughfare, placemark.name];
        selectMark = placemark;
    }
    else {
        MKMapItem *item = self.locations[indexPath.row];
        CLPlacemark *placemark = item.placemark;
        selectMark = placemark;
        name = item.name;
    }
    self.positionSelectBlock ? self.positionSelectBlock (selectMark, name) : nil;
}

- (UITableView *)tbl {
    if (!_tbl) {
        _tbl = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavagationBarH + KScaleWidth(52.0), self.width, self.height - kNavagationBarH)];
        _tbl.delegate = self;
        _tbl.dataSource = self;
//        [_tbl registerClass:<#(nullable Class)#> forCellReuseIdentifier:<#(nonnull NSString *)#>];
        if (@available(iOS 15.0, *)) {
            _tbl.sectionHeaderTopPadding = 0;
        } else {
            _tbl.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            // Fallback on earlier versions
        }
    }
    return _tbl;
}

- (UITextField *)searchTextField {
    if (!_searchTextField) {
        _searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(KScaleWidth(20.0), kNavagationBarH + KScaleWidth(10.0), self.width - KScaleWidth(20.0)*2, KScaleWidth(32.0))];
        _searchTextField.placeholder = @"搜索附近位置";
        _searchTextField.returnKeyType = UIReturnKeySearch;
        _searchTextField.delegate = self;
    }
    return _searchTextField;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
